<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类别" prop="categoryId">
        <el-tree-select
            v-model="queryParams.categoryId"
            :data="categoryOptions"
            value-key="id"
            check-strictly
            :render-after-expand="false"
            :props="{ value: 'id', label: 'name', children: 'children' }"
        />
      </el-form-item>

      <!--****************************-->
      <el-form-item label="状态" prop="enableFlag">
        <el-select v-model="queryParams.enableFlag" clearable placeholder="选择状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!--****************************-->
      <br>
      <el-form-item label="物品编码" prop="parentCode">
        <el-input
            v-model="queryParams.parentCode"
            placeholder="请输入物品编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物品名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入物品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeUpdateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['md:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['md:goods:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['md:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['md:goods:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="物品编码" align="center" prop="parentCode"/>
      <el-table-column label="物品名称" align="center" prop="name"/>
      <el-table-column label="规格型号" align="center" prop="specification"/>
      <el-table-column label="计量单位" align="center" prop="measureUnit">
      <template #default="scope">
        <dict-tag :options="wms_goods_measure_unit" :value="scope.row.measureUnit"/>
      </template>
      </el-table-column>
      <el-table-column label="包装单位" align="center" prop="packingUnit">
      <template #default="scope">
        <dict-tag :options="wms_goods_measure_unit" :value="scope.row.packingUnit"/>
      </template>
      </el-table-column>
      <el-table-column label="包装数量" align="center" prop="packingQuantity"/>
<!--      <el-table-column label="商城商品" align="center" prop="isShop"/>-->
<!--      <el-table-column label="是否物料" align="center" prop="isMaterial"/>-->
<!--      <el-table-column label="是否生产品" align="center" prop="isProduct"/>-->
<!--      <el-table-column label="是否库存" align="center" prop="isStock"/>-->
<!--      <el-table-column label="是否销售" align="center" prop="isCrm"/>-->
      <el-table-column label="是否启用" align="center" prop="enableFlag">
        <template #default="scope">
          <dict-tag :options="sys_state" :value="scope.row.enableFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="类型ID" align="center" prop="categoryId"/>
      <el-table-column label="类型" align="center" prop="categoryName"/>
      <el-table-column label="备注" align="center" prop="remark"/>
<!--      <el-table-column label="创建者" align="center" prop="createBy"/>-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="更新者" align="center" prop="updateBy"/>-->
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="180" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['md:goods:edit']">
            修改物品
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdateGoodsLine(scope.row)"
                     v-hasPermi="['md:goods:edit']">
            物品数据明细
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['md:goods:remove']">删除物品
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改物品对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入物品名称"/>
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <!--        ****************************************************-->
        <el-form-item label="类别" prop="categoryId">
          <el-tree-select
              v-model="form.categoryId"
              :data="categoryOptions"
              value-key="id"
              check-strictly
              :render-after-expand="false"
              :props="{ value: 'id', label: 'name', children: 'children' }"
          />
        </el-form-item>
        <!--        ****************************************************-->

        <el-form-item label="计量单位" prop="measureUnit">
          <el-select v-model="form.measureUnit" placeholder="请选择计量单位">
            <el-option
                v-for="dict in wms_goods_measure_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包装单位" prop="packingUnit">
          <el-select v-model="form.packingUnit" placeholder="请选择包装单位">
            <el-option
                v-for="dict in wms_goods_measure_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包装数量" prop="packingQuantity">
          <el-input v-model="form.packingQuantity" placeholder="请输入包装数量"/>
        </el-form-item>

<!--        <el-form-item label="商城商品" prop="isShop">-->
<!--          <el-input v-model="form.isShop" placeholder="请输入商城商品"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否物料" prop="isMaterial">-->
<!--          <el-input v-model="form.isMaterial" placeholder="请输入是否物料"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否生产品" prop="isProduct">-->
<!--          <el-input v-model="form.isProduct" placeholder="请输入是否生产品"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否库存" prop="isStock">-->
<!--          <el-input v-model="form.isStock" placeholder="请输入是否库存"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否销售模块可用" prop="isCrm">-->
<!--          <el-input v-model="form.isCrm" placeholder="请输入是否销售模块可用"/>-->
<!--        </el-form-item>-->
        <!--        ****************************************************-->
        <br>
        <el-form-item label="是否启用" prop="enableFlag">
          <el-switch v-model="form.enableFlag"
                     active-text="启用"
                     active-value="0"
                     inactive-text="停用"
                     inactive-value="1"/>
        </el-form-item>
        <!--        ****************************************************-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
<!--        <el-form-item label="租户id" prop="tenantId">-->
<!--          <el-input v-model="form.tenantId" placeholder="请输入租户id"/>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物品数据明细 添加或修改物品对话框 -->
    <el-dialog :title="goodsLine.title" v-model="goodsLine.open" width="900px" append-to-body>
      <el-divider content-position="center">物品信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAddMdGoodsLine">添加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="Check" @click="">保存</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="Delete" @click="handleDeleteMdGoodsLine">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="Close" @click="goodsLine.open = false">关闭</el-button>
        </el-col>
      </el-row>
      <el-table :data="goodsLine.list" :row-class-name="rowMdGoodsLineIndex"
                @selection-change="handleMdGoodsLineSelectionChange" ref="mdGoodsLine">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="价格" prop="price" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.price" placeholder="请输入价格"/>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" prop="enableFlag" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.enableFlag" placeholder="请输入是否启用"/>
          </template>
        </el-table-column>
        <el-table-column label="是否设置安全库存" prop="safeStockFlag" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.safeStockFlag" placeholder="请输入是否设置安全库存"/>
          </template>
        </el-table-column>
        <el-table-column label="最低库存量" prop="minStock" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.minStock" placeholder="请输入最低库存量"/>
          </template>
        </el-table-column>
        <el-table-column label="最大库存量" prop="maxStock" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.maxStock" placeholder="请输入最大库存量"/>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/md/goods";


import {ref} from 'vue'
import {listTree} from "@/api/md/tree";

const {proxy} = getCurrentInstance();

const goodsList = ref([]);
const mdGoodsLineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMdGoodsLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);
const daterangeCreateTime = ref([]);
const {sys_state,wms_goods_measure_unit} = proxy.useDict( 'sys_state','wms_goods_measure_unit');

const data = reactive({
  form: {
    categoryId: 1,
  },
  queryParams: {
    categoryId: 1,
    pageNum: 1,
    pageSize: 10,
    parentCode: null,
    name: null,
    specification: null,
    updateTime: null,
    packingUnit:null,
    measureUnit:null,
    enableFlag:null
  },
  rules: {}
});
const {queryParams, form, rules} = toRefs(data);
const categoryOptions = ref([]);
const options = [
  {
    value: '0',
    label: '启用',
  },
  {
    value: '1',
    label: '停用',
  },
]
/*** 订单明细参数 */
const goodsLine = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "订单明细",
  //表格数据
  list: []
});

/** 新增按钮操作 */
function handleUpdateGoodsLine(row) {

  goodsLine.open = true;
  goodsLine.title = row.name;

}

/** 查询物品列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
  });

  getGoodsTree(queryParams.value.categoryId);
  loading.value = false;
}

function getGoodsTree(categoryId) {
  listTree({parentId: categoryId}).then(response => {
    categoryOptions.value = proxy.handleTree(response.data, "id");
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    parentCode: null,
    name: null,
    specification: null,
    packingUnit: null,
    measureUnit: null,
    packingQuantity: null,
    isShop: null,
    isMaterial: null,
    isProduct: null,
    isStock: null,
    isCrm: null,
    enableFlag: null,
    categoryId: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    tenantId: null
  };
  mdGoodsLineList.value = [];
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.parentCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加物品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _parentCode = row.parentCode || ids.value
  getGoods(_parentCode).then(response => {
    form.value = response.data;
    mdGoodsLineList.value = response.data.mdGoodsLineList;
    open.value = true;
    title.value = "修改物品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      form.value.mdGoodsLineList = mdGoodsLineList.value;
      if (form.value.parentCode != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _parentCodes = row.parentCode || ids.value;
  proxy.$modal.confirm('是否确认删除物品编号为"' + _parentCodes + '"的数据项？').then(function () {
    return delGoods(_parentCodes);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 物料产品序号 */
function rowMdGoodsLineIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 物料产品添加按钮操作 */
function handleAddMdGoodsLine() {
  let obj = {};
  obj.price = "";
  obj.attrValue = "";
  obj.enableFlag = "";
  obj.safeStockFlag = "";
  obj.minStock = "";
  obj.maxStock = "";
  obj.remark = "";
  obj.createBy = "";
  obj.createTime = "";
  obj.updateBy = "";
  obj.updateTime = "";
  obj.tenantId = "";
  goodsLine.list.push(obj);
}

/** 物料产品删除按钮操作 */
function handleDeleteMdGoodsLine() {
  if (checkedMdGoodsLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物料产品数据");
  } else {
    const mdGoodsLines = mdGoodsLineList.value;
    const checkedMdGoodsLines = checkedMdGoodsLine.value;
    mdGoodsLineList.value = mdGoodsLines.filter(function (item) {
      return checkedMdGoodsLines.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleMdGoodsLineSelectionChange(selection) {
  checkedMdGoodsLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('md/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

getList();
</script>
